package com.weng.coder.service.generateCode;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import java.io.FileNotFoundException;
import java.io.Writer;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import com.weng.coder.common.model.File;


/**
 * 从文件系统读取Freemarker模板并处理
 *
 * @author wengzhonghui
 */
@Service("fileFreemarkerProccesor")
@Slf4j
public class FileFreemarkerProccesorImpl implements FreemarkerProccesor {


    @Override
    public void processTemplate(File file, Map freemarkerModel, Writer writer) {
        try {
            java.io.File dir = new java.io.File(file.getPath());
            Configuration configuration = new Configuration();
            configuration.setDirectoryForTemplateLoading(dir);
            configuration.setObjectWrapper(new DefaultObjectWrapper());
            configuration.setOutputEncoding("UTF8");

            freemarker.template.Template template = configuration.getTemplate(file.getName() + file.getExtension(), "UTF8");
            template.process(freemarkerModel, writer);
        } catch (FileNotFoundException e) {
            log.error("模板文件不存在", e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
